package com.base.home.act;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.event.ImagePath;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.home.R;
import com.base.home.databinding.ActivityPathviewBinding;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * 签名图片
 * Created by weikailiang on 2020/2/24.
 */
@Route(path = "/home/pahtview")
public class PathViewActivity extends CBaseBarMvpActivity{
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private ActivityPathviewBinding mBinding;
    private String path = null;
    @Autowired
    String type;
    @Override
    protected int getLayoutResource() {
        return R.layout.activity_pathview;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityPathviewBinding) mRootBinding;
        setBackNavigation();
        setBarTitle("签名");
        setRigImg(R.drawable.ic_title_share, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(path)){
                    showMes("请先保存签名");
                    return;
                }
                File f = new File(path);
                UMImage thumb = new UMImage(mContext,f);
                new ShareAction(PathViewActivity.this)
                        .withMedia(thumb)
                        .withText("签名分享")
                        .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.ALIPAY,SHARE_MEDIA.DINGTALK)
                        .setCallback(shareListener).open();
            }
        });
    }
    //分享回调
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            showMes("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showMes("分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showMes("分享取消了");
        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
    @Override
    protected void start() {
        mBinding.reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBinding.pathView.clear();
            }
        });
        mBinding.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    //检测是否有写的权限
                    int permission = ActivityCompat.checkSelfPermission(PathViewActivity.this,
                            "android.permission.WRITE_EXTERNAL_STORAGE");
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        // 没有写的权限，去申请写的权限，会弹出对话框
                        ActivityCompat.requestPermissions(PathViewActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = viewToBitmap(mBinding.pathView);
                if (null != bitmap) {
                    saveBitmap(bitmap);
                }
            }
        });
    }
    private Bitmap viewToBitmap(View view) {
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    /**
     * 把bitmap本地然后存到相册，然后插入相册uri ，在发广播通知相册更新
     *
     * @param bitmap
     */
    private void saveBitmap(Bitmap bitmap) {
        File qrCache = new File(getExternalCacheDir(), "cache");//储存路径可以存在内部存储
        if (!qrCache.exists()) {
            qrCache.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";//图片文件名字
        File picFile = new File(qrCache, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(picFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //插入相册uri
        try {
            String result = MediaStore.Images.Media.insertImage(getContentResolver(),
                    picFile.getAbsolutePath(), picFile.getName(), null);
            Uri.parse(result);
            //发送广播，发送广播这里注意，只要更新你存的路径就好了，如果更新整个sdk 速度将会非常慢
            Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            sendBroadcast(scannerIntent);
            path = picFile.getAbsolutePath();
            showMes("图片保存成功");
            if (!TextUtils.isEmpty(type)){
                ImagePath imagePath = new ImagePath();
                imagePath.setPath(path);
                imagePath.setType(type);
                RxBus2.getInstance().post(imagePath);
                finish();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            showMes("图片保存失败");
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        System.gc();
    }

}
